package com.hontlong.toy.parrot;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ZhiDaoParser implements Parser {

	private static Pattern p = Pattern
			.compile("(?s)(?i)<a\\s+name=\"\\d+\"\\s+/>\\s*<div\\s+.*?>(.*?)</div>");

	@Override
	public Ask parser(final String html) {
		if (html.indexOf("问题已失效或不存在") >= 0) {
			return null;
		}
		final Ask ask = new Ask();
		// <cc><a href="/browse/74?lm=9">电脑/网络</a> &gt; <a
		// href="/browse/91?lm=9">多媒体</a></cc>
		int start = html.indexOf("<cc>") + "<cc>".length();
		int end = html.indexOf("</cc>");
		if ((start > 0) && (end > 0) && (end > start)) {
			String tmp = html.substring(start, end);
			tmp = TransUtil.delWebCodeChar(tmp);
			ask.setType(tmp);
		}
		start = html.indexOf("<cq>", end) + "<cq>".length();
		end = html.indexOf("</cq>", start);
		if ((start > 0) && (end > 0) && (end > start)) {
			ask.setAskTitle(html.substring(start, end));
			ask.setAskTitle(TransUtil.unicodeTextDecode(ask.getAskTitle())
					.toString());
		} else {
			return null;
		}
		// <cd>什么小吃大家容易接受，大家还愿意吃，求精。</cd>
		start = html.indexOf("<cd>", end) + "<cd>".length();
		end = html.indexOf("</cd>", start);
		if ((start > 0) && (end > 0) && (end > start)) {
			String temp = html.substring(start, end);
			temp = TransUtil.unicodeTextDecode(temp).toString();
			temp = TransUtil.delWebCodeChar(temp);
			ask.setAsk(html.substring(start, end));
		}
		// 回答
		// <a name="157333505" />
		// <div class="f14 p90 pl10"> 天津的煎饼果子<br>只要是正宗在哪都好卖</div>
		final Matcher m = ZhiDaoParser.p.matcher(html);
		for (; m.find();) {
			String answer = m.group(1);
			if (answer != null) {
				answer = TransUtil.unicodeTextDecode(answer).toString();
				answer = TransUtil.delWebCodeChar(answer);
				ask.getAnswers().add(answer);
			}
		}
		return ask;
	}
}
